#version 130
uniform samplerCube visMap;
uniform vec3 shooterPos;
uniform vec3 axisX;
uniform vec3 axisY;
uniform vec3 oriPos;
uniform vec3 normEmitter;
uniform vec3 normReceiver;
uniform vec3 shooterEnergy;
uniform sampler2D shooterDiffuseMap;
uniform vec3 shooterCoord;
uniform vec4 polyID;
uniform float areaEmitter;
uniform float areaReceiver;
centroid in vec2 coord;
flat in vec3 norm1, norm2, norm3;

out vec4 residual;
out vec4 radiosity1;
out vec4 radiosity2;
out vec4 radiosity3;

void main()
{
	vec3 recvPos = oriPos + axisX * coord.x + axisY * coord.y;
	vec3 r = shooterPos - recvPos;
	float dist2 = dot(r,r);
	r = normalize(r);
	float cosi = max(dot(normReceiver, r),0);
	float cosi1 = max(dot(norm1, r),0);
	float cosi2 = max(dot(norm2, r),0);
	float cosi3 = max(dot(norm3, r),0);
	float cosj = max(-dot(normEmitter, r),0);

	float divider = (3.1415926 * dist2 + areaEmitter);

	float F = cosi*cosj/divider;
	float F1 = cosi1*cosj / divider;
	float F2 = cosi2*cosj / divider;
	float F3 = cosi3*cosj / divider;

	float visible = (texture(visMap, -r) == polyID)?1.0:0.0;
	F *= visible;
	F1 *= visible;
	F2 *= visible;
	F3 *= visible;
	vec3 shooterColor = texture(shooterDiffuseMap, shooterCoord.xy).xyz;
	vec3 rs = shooterEnergy * shooterColor * areaEmitter * F; 
	residual = vec4(rs,0.0);
	radiosity1 = vec4(shooterEnergy * shooterColor * areaEmitter * F1,0.0);
	radiosity2 = vec4(shooterEnergy * shooterColor * areaEmitter * F2,0.0);
	radiosity3 = vec4(shooterEnergy * shooterColor * areaEmitter * F3,0.0);
}